﻿using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using Winton.Extensions.Configuration.Consul;
using Zhongjiu.Common;

namespace Zhongjiu.Extensions
{
  /// <summary>
  /// Consul 注册服务
  /// </summary>
  public static class ConsulMiddleware
  {
    /// <summary>
    /// 使用Consul服务注册与发现
    /// </summary>
    /// <param name="app"></param>
    /// <param name="lifetime"></param>
    /// <returns></returns>
    public static IApplicationBuilder UseConsulRegistMiddle(this IApplicationBuilder app, IHostApplicationLifetime lifetime)
    {
      if (Appsettings.app("Consul:EnabledRegister").ToBool())
      {
        var consulClient = new ConsulClient(c =>
       {
                 //consul地址
         c.Address = new Uri(Appsettings.app("Consul:Address"));
       });

        var registration = new AgentServiceRegistration()
        {
          ID = Guid.NewGuid().ToString(),//服务实例唯一标识
          Name = Appsettings.app("Consul:ServiceName"),//服务名
          Address = Appsettings.app("host"), //服务IP
          Port = int.Parse(Appsettings.app("port")),//服务端口
          Check = new AgentServiceCheck()
          {
            DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(2),//服务启动多久后注册
            Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔
            HTTP = $"http://{Appsettings.app("host")}:{Appsettings.app("port")}{Appsettings.app("Consul:ServiceHealthCheck")}",//健康检查地址
            Timeout = TimeSpan.FromSeconds(5)//超时时间
          }
        };

        //服务注册
        consulClient.Agent.ServiceRegister(registration).Wait();

        //应用程序终止时，取消注册
        lifetime.ApplicationStopping.Register(() =>
        {
          consulClient.Agent.ServiceDeregister(registration.ID).Wait();
        });

      }
      return app;
    }

    /// <summary>
    /// 使用Consul配置中心
    /// </summary>
    /// <param name="config"></param>
    /// <param name="context"></param>
    public static void AddConsulConfigCenterSetup(this IConfigurationBuilder config, HostBuilderContext context)
    {
      if (Appsettings.app("Consul:EnabledConfigCenter").ToBool())
      {
        //需要添加nuget:Winton.Extensions.Configuration.Consul
        var env = context.HostingEnvironment;
        var consulAddress = Appsettings.app("Consul:Address");
        config.AddConsul($"{env.ApplicationName}/appsettings.json", options =>
        {
          options.ReloadOnChange = true;
          options.Optional = true;
          options.OnLoadException = e => e.Ignore = true;
          options.ConsulConfigurationOptions = ccc =>
          {
            ccc.Address = new Uri(consulAddress);
          };
        });
        config.AddConsul($"{env.ApplicationName}/appsettings.{env.EnvironmentName}.json", options =>
        {
          options.ReloadOnChange = true;
          options.Optional = true;
          options.OnLoadException = e => e.Ignore = true;
          options.ConsulConfigurationOptions = ccc =>
          {
            ccc.Address = new Uri(consulAddress);
          };
        });
        config.AddConsul($"{env.ApplicationName}/appsettings.{Appsettings.app("host")}.{Appsettings.app("port")}.json", options =>
        {
          options.ReloadOnChange = true;
          options.Optional = true;
          options.OnLoadException = e => e.Ignore = true;
          options.ConsulConfigurationOptions = ccc =>
          {
            ccc.Address = new Uri(consulAddress);
          };
        });
      }
    }
  }
}
